<?php
if(!defined('X2')) die("Direct inclusion");
require_once(X2 ."/classes/myDB/myDB.class.php");

class Listing {
  // Основные параметры
  var $baseURL = '';
  var $offset = 0;
  var $limit = 10;
  var $page = 0;
  var $sortBy = 'position';
  var $sortOrder = 'ASC';
  var $createRSS = false;
  var $expanded = false;

  // Фильтрация по ключевым словам и категориям
  var $keyword = '';
  var $category = 0;

  var $items = array();

  var $prefix = 'x2_';
  var $tmpTable = "x2_listing";

  function Listing ($baseURL, $page = 0, $params = array()){  	$this -> baseURL = $baseURL;
  	$this -> page = intval($page);
    $this -> db =& myDB::getConnection2(
      "mysql://" . X2_SQL_USER .":". X2_SQL_PASS ."@". X2_SQL_HOST ."/". X2_SQL_DB
    );
    $this -> db -> debug = true;

    $this -> tmpTable = "x2_listing". strtr($this -> baseURL, "/", "_");

    // Ужас, но пока ничего лучше не придумал
    if(isset($params['offset'])) $this -> offset = (int)$params['offset'];
    if(isset($params['limit'])) $this -> limit = (int)$params['limit'];
    if(isset($params['sort-by'])) $this -> sortBy = $params['sort-by'];
    if(isset($params['sort-order'])) $this -> sortOrder = $params['sort-order'];
    if(isset($params['keyword'])) $this -> keyword = $params['keyword'];
    if(isset($params['category'])) $this -> category = (int)$params['category'];

    $sBy = array("position", "title", "ctime", "mtime", "random");
    $sOrder = array("ASC", "DESC");

    if(!in_array(strtolower($this -> sortBy), $sBy)) {
      $this -> sortBy = $sBy[0];
    }
    if($this -> sortBy == 'random') $this -> sortBy = "RAND()";
    if(!in_array(strtoupper($this -> sortOrder), $sOrder)) {
      $this -> sortOrder = $sOrder[0];
    }
    $this -> sortBy = $this -> db -> quote($this -> sortBy);
    $this -> sortOrder = strtoupper($this -> sortOrder);
    $this -> limit = intval($this -> limit);
    $this -> offset = intval($this -> limit) * intval($this -> page);
    $this -> expanded = (bool)$this -> expanded;
    $this -> keyword = $this -> db -> quote(trim($this -> keyword));
    $this -> category = intval($this -> category);

    $c = substr_count($this -> baseURL, '/') + 1;
    $quotedURL = $this -> db -> quote($this -> baseURL);
    $this -> db -> query(
        "CREATE TEMPORARY TABLE IF NOT EXISTS `{$this -> tmpTable}`
        SELECT t.*
        FROM `x2_tree` AS t". (($this -> category > 0)? ",
        `x2_doc_label_ref` AS ref" : "") ."
        WHERE
        LEFT(url, LENGTH('{$quotedURL}/')) = '{$quotedURL}/' AND
        LOCATE('/', url, LENGTH('{$quotedURL}/') + 1) = 0 AND
        t.visible = 'yes'". (($this -> category > 0)? " AND
        catRef.label = {$this -> category} AND
        catRef.docId = t.id" : "")."
        ". (($this -> keyword != '')? " AND
        t.keywords LIKE '%{$this -> keyword}%'
        " : "")
    );
//    exit(var_export($this -> db, 1));
  }

  function get(){
    $c = $this -> db -> arrayQuery(
      "SELECT * FROM `{$this -> tmpTable}`
      ORDER BY {$this -> sortBy} {$this -> sortOrder}
      LIMIT {$this -> offset}, {$this -> limit}"
    );
    if(count($c) > 0){
      $this -> items = $c;
      return true;
    } else {
      return false;
    }
  }

  function total(){
    $c = $this -> db -> getSingle(
      "SELECT COUNT(*) AS q FROM `{$this -> tmpTable}`",
      "q"
    );
    return ($c)? $c : 0;
  }

  function getBaseURL(){
    return $this -> baseURL;
  }

  function getIdByURL($url){
    $c = $this -> db -> getSingle(
      "SELECT id FROM `x2_tree`
      WHERE url = '". $this -> db -> quote($this -> baseURL),
      "id"
    );
    return $c? $c : 0;
  }

  function itemToXML ($item = array()){
    $xmlStr = '';
    $xmlStr .= '<x:block name="link">';
    $xmlStr .= '<x:param name="href" value="'. $item['url'] .'"/>';
    $xmlStr .= '<x:param name="ctime" value="'. $item['ctime'] .'"/>';
    $xmlStr .= '<x:param name="mtime" value="'. $item['mtime'] .'"/>';
    $xmlStr .= '<x:param name="thumbnail" value="'. $item['thumbnail'] .'"/>';
    $xmlStr .= '<x:title>'. $item['title'] .'</x:title>';
    $xmlStr .= '<x:description>'. $item['description'] .'</x:description>';
    $xmlStr .= '</x:block>';
    return $xmlStr;
  }

  function getPager(){  	$xmlStr = '';  	$total = $this -> total();
    if($total > count($this -> items)){      $start = max(0, $this -> page - 5);
      $end = min(ceil($total / $this -> limit), $start + 10);      $xmlStr .= '<x:block name="pager">';
      $xmlStr .= '<x:param name="current" value="'. $this -> page .'"/>';
      for($i = $start; $i < $end; $i++){        $xmlStr .= '<x:param name="page" value="'. $i .'"/>';      }
      $xmlStr .= '</x:block>';
    }    return $xmlStr;
  }
}
?>